package org.jeecg.config.shiro.filters;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.shiro.JwtToken;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * 员工登录鉴权拦截器
 */
@Slf4j
public class EmployeeJwtFilter extends JwtFilter {

    /**
     * 重写父类方法，使用员工Token前缀
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader(CommonConstant.X_ACCESS_TOKEN);
        
        if (oConvertUtils.isEmpty(token)) {
            token = httpServletRequest.getParameter("token");
        }
        
        if (StringUtils.isBlank(token)) {
            throw new AuthenticationException("token不能为空!");
        }
        
        // 校验token是否存在于redis中
        RedisUtil redisUtil = SpringContextUtils.getBean(RedisUtil.class);
        Object redisToken = redisUtil.get(CommonConstant.PREFIX_EMPLOYEE_TOKEN + token);
        if (redisToken == null) {
            log.info("员工Token已过期或不存在");
            throw new AuthenticationException(CommonConstant.TOKEN_IS_INVALID_MSG);
        }
        
        JwtToken jwtToken = new JwtToken(token);
        // 提交给realm进行登入，如果错误他会抛出异常并被捕获
        getSubject(request, response).login(jwtToken);
        // 如果没有抛出异常则代表登入成功，返回true
        return true;
    }
} 